<?php

namespace app\delivery\controller;
use icontroller\wechat\AController;
use library\common\wechat_msg\send_msg;
use library\order\format;
use library\tencent\wechat\admin_wechat\SendTemplateMessage;
use model\Account;
use model\AccountPayment;
use model\AccountRole;
use model\AccountWechat;
use model\ShopGoods;
use model\ShopOrder;
use model\ShopOrderGoods;
use model\ShopOrderItem;
use model\ShopGoodsVariant;
use model\ShopStore;
use think\Db;
use think\Request;

/**
 * User: lsx
 * Date: 2017/5/20
 * Time: 11:42
 * Progress:0%
 */
class Order extends AController
{
    protected $beforeActionList = [
        "isLogin","isDelivery"
    ];
    public function isDelivery(){
        $ar = AccountRole::get(["account_id" => $this->account_id, "role_id" => 2, "flag_delete" => 0]);
        if (empty($ar) ) {
           $this->redirect('shop/Shop/index');
        }
    }
    public function index()
    {
        $request = Request::instance();
        if ($request->isAjax()) {
            $page = input('page', 0);                      //分页
            $count = config('paginate.list_rows');          //每页数量
            $flag_pay = input("flag_pay");
            $flag_status = input("flag_status", 0);
            $mo = new ShopOrder();
            $where = [];
            if ($flag_pay != null) {
                $where["flag_pay"] = $flag_pay;
            }
            if ($flag_status != null && $flag_status != 4) {
                $where["flag_status"] = $flag_status;
            } else {
                $where["flag_status"] = ["<>", 4];
            }
            if ($flag_status == 0) {
                $where["flag_status"] = ["in", [0, 5]];
            }
            if ($flag_status == 1) {
                $where["flag_status"] = ["in", [1, 6]];
            }
            if (!in_array($flag_status, [0, 5])) {
                $where["delivery_account_id"] = $this->account_id;
            }

            $list = $mo->where($where)->where("flag_pay|flag_delivery", "<>", 0)->page($page, $count)->order(["op_time"=>"desc"])->select();
            $d_list = $list;
            foreach ($d_list as $ik => $iv) {
                $item_list = ShopOrderItem::all(["order_id" => $iv["id"]]);
                $order_item = [];
                foreach ($item_list as $k => $v) {
                    $order_item[] = [
                        "store_name" => $v->shopStore->name,
                        "logo" => $v->shopStore->logo,
                        "pay_amount" => $v->pay_amount
                    ];
                }
                $d_list[$ik]["order_items"] = $order_item;
            }

            $this->success("获取数据成功!", null, $d_list);
        }

        return view();
    }

    public function detail()
    {
        $ps = input("ps",0);
        $order_id = input("order_id");
        if (!empty($order_id) ){
            $order = ShopOrder::get($order_id);
            if (!empty($order)){
                if ($order->delivery_account_id>0&&$order->delivery_account_id==$this->account_id){
                    $ps = 0;
                }
            }
        }
        $this->assign("order_id", $order_id);
        $this->assign("ps",$ps);
        return view();
    }

    public function detail_data()
    {
        $order_id = input("order_id");

        $list = ShopOrderItem::all(["order_id" => $order_id]);
        $d_list = $list;

        foreach ($list as $k => $v) {
            $shopGoods = [];
            $d_list[$k]->shopStore = $v->shopStore;
            foreach ($v->shopOrderGoods as $k1 => $v1) {
                $name = $v1->shopGoods->name;
                $price = $v1->shopGoods->price;
                if ($v1->variant_id > 0) {
                    $variant = ShopGoodsVariant::get($v1->variant_id);
                    if ($variant) {
                        $name = $name . "(" . $variant->name . ")";
                        $price = $variant->price;
                    }
                }
                $shopGoods[] = [
                    "name" => $name,
                    "quantity" => $v1->quantity,
                    "amount" => $price
                ];
            }
            $d_list[$k]->shopGoods = $shopGoods;
        }
        //配送信息
        $info = ShopOrder::get($order_id);
        if ($info){
            $info = $info->getData();
        }
        $info["flag_status_text"] = format::order_status($info["flag_status"]);
        $this->success("获取数据成功!", null, ["list" => $d_list, "info" => $info]);
    }

    public function statistics()
    {
        //已配送订单总额
        $bg_time = input("bg_time");
        $end_time = input("end_time");
        $so = new ShopOrder();

        $where = [
            "delivery_account_id" => $this->account_id,
            "flag_status" => ["in", [1, 6]]
        ];
        $where1 = [
            "delivery_account_id" => $this->account_id,
            "flag_status" => 7
        ];
        if (!empty($end_time) && !empty($bg_time)) {
            $where["order_time"] = ["between", [strtotime($bg_time), strtotime($end_time)+60]];
            $where1["order_time"] = ["between", [strtotime($bg_time), strtotime($end_time)+60]];
        }
        $ups_money = $so->where($where1)->sum("order_amount");
        $ups_count = $so->where($where1)->count();
        $ps_money = $so->where($where)->sum("order_amount");
        $ps_count = $so->where($where)->count();
        $min_time = $so->min("order_time");
        $max_time = $so->max("order_time");
        $data = [
            "ps_money" => $ps_money > 0 ? $ps_money : 0,
            "ps_count" => $ps_count > 0 ? $ps_count : 0,
            "ups_money" => $ups_money > 0 ? $ups_money : 0,
            "ups_count" => $ups_count > 0 ? $ups_count : 0,
            "min_time" => empty($bg_time) ? date("Y-m-d H:i", $min_time) : $bg_time,
            "max_time" => empty($end_time) ? date("Y-m-d H:i", $max_time) : $end_time
        ];

        $this->assign("data", $data);
        $request = Request::instance();
        if ($request->isAjax()) {
            $this->success("获取成功!", null, $data);
        }
        return view();
    }

    // <editor-fold defaultstate="collapsed" desc="开始配送">
    public function delivery()
    {
        $order_id = input("order_id");

        $info = ShopOrder::get($order_id);
        if ($info){
            $info = $info->getData();
        }else{
            $this->error("订单已取消货不存在!");
        }
        $ret = AccountRole::get(["account_id" => $this->account_id, "role_id" => 2]);
        $mo = new ShopOrderItem();
        if (empty($ret)) {
            $this->error("您不是配送人员!");
        }
        if ($info["flag_status"] == 1) {
            $this->error("此订单已配送!");
        }
        if (!in_array($info["flag_status"], [1, 2, 3, 4])) {
            $ps_time = time();
            Db::startTrans();
            $flag_status = 1;
            if ($info["flag_status"] == 0) {
                $flag_status = 1;
            }
            if ($info["flag_status"] == 5) {
                $flag_status = 6;
            }
            $result = ShopOrder::update(["flag_status" => $flag_status, "delivery_account_id" => $this->account_id,"ps_time"=>$ps_time], ["id" => $order_id]);
            if (!$result) {
                Db::rollback();
                $this->error("操作订单出错1!");
            }
            $result = ShopOrderItem::update(["flag_status" => $flag_status, "delivery_account_id" => $this->account_id,"ps_time"=>$ps_time], ["order_id" => $order_id]);
            if (!$result) {
                Db::rollback();
                $this->error("操作订单出错3!");
            }

            Db::commit();
            //消息模板
//            $oauth = AccountWechat::get(['account_id' => $info["account_id"]]);
//            $openid = $oauth['openid'];
//            $data = array(
//                'touser' => $openid,
//                'keyword1' => $info['order_sn'],
//                'keyword2' => "配送员配送中",
//                'keyword3' => date('Y-m-d', $info["pay_time"]),
//                'keyword4' => "外卖",
//                'keyword5' => $info['order_amount'] . '元'
//            );
//            SendTemplateMessage::send_message("OPENTM204987032", $data);

            $oauth = AccountWechat::get(['account_id' => $info["account_id"]]);
            $openid = $oauth['openid'];
            $shopOrderGoods = new ShopOrderGoods();
            $shopGoods = new ShopGoods();
           // $shopStore = new ShopStore();
            $orderItems = $mo->where(["order_id" => $order_id])->field("id,store_id")->select();
            if (!empty($orderItems)) {
                $orderItems = $orderItems->toArray();
                $orderItemIds = array_column($orderItems, "id");
              //  $orderItemStoreIds = array_column($orderItems, "store_id");
                $goods_id = $shopOrderGoods->where(["order_item_id" => ["in", $orderItemIds]])->column("goods_id");
                $goods = $shopGoods->where(["id" => ["in", $goods_id]])->column("name");
            //    $stores = $shopStore->where(["id" => ["in", $orderItemStoreIds]])->column("name");
//            $data = array(
//                'touser' => $openid,
//                'keyword1' => $info['order_sn'],
//                'keyword2' => "用户确认收货",
//                'keyword3' => date('Y-m-d', $info["pay_time"]),
//                'keyword4' => "外卖",
//                'keyword5' => $info['order_amount'] . '元'
//            );
//            SendTemplateMessage::send_message("OPENTM204987032", $data);
                $delivery_account = Account::get($this->account_id);
                send_msg::ps_msg($openid, $info, $delivery_account, $goods);
            }
            $this->success("操作成功!");
        } else {
            $this->error("操作订单出错2!");
        }
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="货到付款，确认收款">
    public function cash_delivery()
    {
        $order_id = input("order_id");
        $info = ShopOrder::get($order_id);
        if ($info){
            $info = $info->getData();
        }
        $ret = AccountRole::get(["account_id" => $this->account_id, "role_id" => 2]);
        if (!$ret) {
            $this->error("您不是配送人员!");
        }
        if ($info["flag_pay"] == 1) {
            $this->error("此订单已支付!");
        }
        if (in_array($info["flag_status"], [1, 6])) {
            Db::startTrans();
            $result = ShopOrder::update(["flag_pay" => 1, "flag_status" => 7, "delivery_account_id" => $this->account_id], ["id" => $order_id]);
            if (!$result) {
                Db::rollback();
                $this->error("操作订单出错1!");
            }
            $mo = new ShopOrderItem();
            $payment_ids = $mo->where(["order_id" => $order_id])->column("payment_id");
            $result = AccountPayment::update(["flag_pay" => 1], ["id" => ["in", $payment_ids]]);
            if (!$result) {
                Db::rollback();
                $this->error("操作订单出错3!");
            }
            $result = ShopOrderItem::update(["flag_pay" => 1, "flag_status" => 7, "delivery_account_id" => $this->account_id], ["order_id" => $order_id]);
            if (!$result) {
                Db::rollback();
                $this->error("操作订单出错4!");
            }
            Db::commit();
            $this->success("操作成功!");
        } else {
            $this->error("操作订单出错2!");
        }
    }
    // </editor-fold>


}